<?php

namespace App\Dao;

use App\Model\WithdrawalModel;
use Illuminate\Support\Facades\DB;

class WidthwalDao extends BaseDao
{
    public static function builder_query($params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = WithdrawalModel::query();

        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });

        $query->when(checkIsHasField($params,'withdrawal_id'),function ($query)use ($params){
            $query->where('withdrawal_id',$params['withdrawal_id']);
        });

        $query->when(checkIsHasField($params,'status'),function ($query)use ($params){
            $query->where('status',$params['status']);
        });

        $query->when(checkIsHasField($params,'start_time'),function ($query)use ($params){
            $query->where('created_at','>=',strtotime($params['start_time']));
        });

        $query->when(checkIsHasField($params,'end_time'),function ($query)use ($params){
            $query->where('created_at','<=',strtotime($params['end_time'].' 23:59:59'));
        });

        return $query->orderByDesc('created_at');
    }

    public static function pageinate($params = [])
    {
        return self::builder_query($params)->paginate();
    }

    public static function edit(array $params)
    {
        checkForData(
            ['status'],
            ['请选择操作'],
            $params
        );
        $info = self::info([
            'withdrawal_id'=>$params['withdrawal_id']
        ]);
        DB::beginTransaction();
        try {
            self::builder_query(['withdrawal_id'=>self::deleteParamId($params,'withdrawal_id')])->update(self::filterFields($params,new WithdrawalModel()));
            if($params['status'] == 2){
                //把钱退回去
                BillsDao::moneyUpdate($info['user_id'],bcadd($info['fee'],$info['nums'],2),'提现驳回');
            }
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            self::error('审核失败'.$exception->getMessage());
        }
    }

    public static function info(array $all)
    {
        return self::builder_query($all)->first();
    }
}
